package resp

import (
	"fmt"
	"net/http"
	"time"

	"gin-api-server/core_library/library/constants"

	"github.com/gin-gonic/gin"
)

type SwaggerTemplate struct {
	Code     int    `json:"code" example:"1"`
	Msg      string `json:"msg" example:"相应描述"`
	Data     string `json:"data" example:"返回任意类型"`
	Datetime string `json:"datetime" example:"响应时间"`
}

type responsrData struct {
	Msg      string `json:"msg"`
	Code     int    `json:"code"`
	Data     any    `json:"data"`
	Datetime string `json:"datetime"`
}

func Response(ctx *gin.Context, code int, msg string, data any) {
	ctx.JSON(http.StatusOK, gin.H{
		"msg":      msg,
		"code":     code,
		"data":     data,
		"datetime": time.Now().Format("2006-01-02 15:04:05"),
	})
	ctx.Abort()
	return
}

func Ok(ctx *gin.Context) {
	Response(ctx, constants.ErrorCode.SERVER_SUCCESS, "ok", nil)
}

func OkWithMessage(ctx *gin.Context, message string) {
	Response(ctx, constants.ErrorCode.SERVER_SUCCESS, message, nil)
}

func OkWithData(ctx *gin.Context, data any) {
	Response(ctx, constants.ErrorCode.SERVER_SUCCESS, "ok", data)
}

func OkWithDataAndMsg(ctx *gin.Context, msg string, data any) {
	Response(ctx, constants.ErrorCode.SERVER_SUCCESS, msg, data)
}

func Fail(ctx *gin.Context) {
	Response(ctx, constants.ErrorCode.SERVER_ERROR, "fail", nil)
}

func FailWithMessage(ctx *gin.Context, message string) {
	Response(ctx, constants.ErrorCode.SERVER_ERROR, message, nil)
}

func FailWithData(ctx *gin.Context, data any) {
	Response(ctx, constants.ErrorCode.SERVER_ERROR, "fail", data)
}

func FailWithDataAndMsg(ctx *gin.Context, msg string, data any) {
	Response(ctx, constants.ErrorCode.SERVER_ERROR, msg, data)
}

func FailError(ctx *gin.Context, msg string, err error) {
	Response(ctx, constants.ErrorCode.SERVER_ERROR, fmt.Sprintf("错误(%s) [%s]", msg, err.Error()), nil)
}
